/**
 * cavion（曹仁道）
 * caorendao187@163.com
 * 2017年6月12日 下午10:24:07
 */
package org.rk.core.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * @author cavion @类描述： 2017年6月12日
 */
public class RKSocketUtil {
	public static String method_post="POST";
	public static String method_get="GET";
	public static String reqType_http="HTTP";
	public static String reqType_https="HTTPS";
	
	public static Socket getSocket(String host,int port,String reqType) throws IOException{
		InetAddress address=InetAddress.getByName(host);
		Socket socket=null;
		if(reqType_https.equals(reqType)){
			socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(address, port);
    	}else{
    		socket=SocketFactory.getDefault().createSocket(address, port);
    	}
		return socket;
	}
	public static Socket getHttpSocket(String host,int port) throws IOException{
		return getSocket(host, port, reqType_http);
	}
	public static Socket getHttpsSocket(String host,int port) throws UnknownHostException, IOException{
		return getSocket(host, port, reqType_https);
	}
    public static JSONObject sendReq(String path,Map<String,String> params,String host,int port,String method,String reqType) throws IOException{
    	BufferedWriter bufferedWriter;
    	BufferedReader bufferedReader;
    	//SocketAddress dest = new InetSocketAddress(host, port);
    	String data = genParams(params);
    	
    	Socket socket=null;
    	if(reqType_https.equals(reqType)){
    		socket=getHttpsSocket(host, port);
    	}else{
    		socket=getHttpSocket(host,port);
    	}
        //socket.connect(dest);
        OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
        bufferedWriter = new BufferedWriter(streamWriter);
         
        bufferedWriter.write(method+" " + path + " HTTP/1.1\r\n");
        bufferedWriter.write("Host: " + host + "\r\n");
        if(reqType_https.equals(reqType)&&RkStrUtil.hasText(data)){
        	bufferedWriter.write("Content-Length: " + data.length() + "\r\n");
            bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n");
            bufferedWriter.write(data);
            bufferedWriter.flush();
        }
        bufferedWriter.write("\r\n");
        bufferedWriter.flush();
         
        BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
        bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
        String line = "";
        Long startTime=System.currentTimeMillis();
        System.out.println("请求完成，读取数据："+startTime);
        JSONObject result=new JSONObject();
        while((bufferedReader.readLine())!=null){
        	line=bufferedReader.readLine();
        	System.out.println(line);
        	result=JSONObject.parseObject(line);
        }
        Long endTime=System.currentTimeMillis();
        System.out.println("历时："+(endTime-startTime));
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        return result;
    }
    public static String genParams(Map<String,String> params) throws UnsupportedEncodingException{
    	StringBuilder sbData=new StringBuilder();
    	for (String key : params.keySet()) {
    		if(RkStrUtil.hasText(params.get(key))){
    			if(RkStrUtil.hasText(sbData.toString())){
        			sbData.append("&"+URLEncoder.encode(key, "utf-8")+"="+URLEncoder.encode(params.get(key), "utf-8"));
        		}else{
        			sbData.append(URLEncoder.encode(key, "utf-8")+"="+URLEncoder.encode(params.get(key), "utf-8"));
        		}
    		}
		}
    	return sbData.toString();
    }
    public static JSONObject sendHttpGet(String path,Map<String,String> params,String host,int port) throws IOException{
    	return sendReq(path, params, host, port, method_get, reqType_http);
    }
    public static JSONObject sendHttpPost(String path,Map<String,String> params,String host,int port) throws IOException{
    	return sendReq(path, params, host, port, method_post, reqType_http);
    }
    public static JSONObject sendHttpsGet(String path,Map<String,String> params,String host,int port) throws IOException{
    	return sendReq(path, params, host, port, method_get, reqType_https);
    }
    public static JSONObject sendHttpsPost(String path,Map<String,String> params,String host,int port) throws IOException{
    	return sendReq(path, params, host, port, method_post, reqType_https);
    }
     
    public static void main(String[] args){
    	try {
			RKSocketUtil.sendHttpsPost("/rk/web/core/domain/module/queryList", new HashMap<String, String>(), "www.utqld.com", 443);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
